package cn.ad.service;

import cn.ad.exception.MediaValidateException;
import cn.ad.handler.SqlSessionHandler;
import cn.ad.interceptor.PageParameter;
import cn.ad.model.DropDownModel;
import cn.ad.model.PubSiteModel;
import cn.ad.entity.PubSite;
import cn.ad.entity.Supplier;
import cn.ad.model.ResultSetList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class MediaService {

	@Autowired
	private SqlSessionHandler sqlSessionHandler;
	
	public ResultSetList<PubSiteModel> findMediaList(HashMap<String, Object> initSearchMap, PageParameter pageInfo) {
		List<PubSiteModel> mediaList = sqlSessionHandler.selectList("pubSiteMapper.pubSite:list:page", initSearchMap, pageInfo);
		ResultSetList<PubSiteModel> list = new ResultSetList<PubSiteModel>(pageInfo.getTotalCount(), mediaList);
		return list;
	}

	public PubSite read(Integer id) {
		return sqlSessionHandler.selectOne("pubSiteMapper.selectById", id);
	}

	public PubSite save(PubSite pubSite,boolean isInsert) {
		if(isRepeat(pubSite)){
			throw new MediaValidateException(MediaValidateException.ErrorCode.MEDIA_NAME_REPEAT);
		}
		if(isInsert){
			pubSite.setStatus(1);
			 sqlSessionHandler.insert("pubSiteMapper.insert", pubSite);
		}else{
			 sqlSessionHandler.update("pubSiteMapper.update", pubSite);
		}
		return pubSite;
	}

	public List<DropDownModel> selectSupplierList() {
		return sqlSessionHandler.selectList("supplierMapper.supplier:drop:list",null);
	}

	public List<DropDownModel> selectPubSiteList(Integer supplierId){
		return sqlSessionHandler.selectList("pubSiteMapper.drop:list",supplierId);
	}

	public List<DropDownModel> selectPubSiteList(String resType) {
		return sqlSessionHandler.selectList("pubSiteMapper.pubSite:list:platform",resType);
	}

	public List<DropDownModel> selectPubSiteList(Map<String, Object> params) {
		if(null == params.get("strategyGroupId") || (Integer)params.get("strategyGroupId") == 0) {
			return this.selectPubSiteList(params.get("resType").toString());
		}
		return sqlSessionHandler.selectList("pubSiteMapper.pubSite:list:stargeyGroup:platform",params);
	}

	public void deletePubSite(Integer id) {
		sqlSessionHandler.update("pubSiteMapper.delete", id);
	}

	public int selectSpaceCount(Integer id) {
		return sqlSessionHandler.selectOne("pubSiteMapper.space:count", id);
	}

	public List<Integer> selectPubSiteIds(Integer id) {
		return sqlSessionHandler.selectList("pubSiteMapper.pubsite:id:list", id);
	}
	
	/**
	 * 验证是否存在重复命名
	 */
	private boolean isRepeat(PubSite pubSite){
		return (int)sqlSessionHandler.selectOne("pubSiteMapper.pubSite:checkname",pubSite) >0;
	}
	
	public Supplier readSupplier(Integer id){
		return sqlSessionHandler.selectOne("supplierMapper.selectById", id);
	}

}
